//
//  DrugDetailViewController.m
//  TestARC
//
//  Created by wuxiaoquan on 12-9-28.
//
//

#import "DrugDetailViewController.h"
#import <CommonCrypto/CommonDigest.h>
#import "MyExtensions.h"
#import "JSONKit.h"
#import "DrugResultViewController.h"
#import "DrugWebViewController.h"
#import "WriteCommentViewController.h"
#import "DiseaseListViewController.h"

#define RowHight 44

@interface DrugDetailViewController ()

@end

@implementation DrugDetailViewController

@synthesize commonNameLabel,nameLabel,operationTableView,overlayBtn,nameView,arrowIV;
@synthesize name,commonName,brandName,operationArray,queryId,diseaseArray;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.navigationController setNavigationBarHidden:FALSE animated:NO];
    [self addRoundBound:self.nameView];
    self.title = self.name;
    commonNameLabel.text = commonName;
    nameLabel.text = name;
    [self addRoundBound:self.operationTableView];
    //NSLog(@"commonName = %@,brandName = %@",self.commonName,self.brandName);
    self.overlayBtn.backgroundColor = [UIColor clearColor];
    if ([self.commonName isEqualToString:self.brandName]) {
        [self.overlayBtn setEnabled:NO];
        [self.arrowIV removeFromSuperview];
    } else {
        [self.overlayBtn setEnabled:YES];
    }
    self.operationArray = [NSArray array];
    
    [self setOperationView];
}

-(void)loadNetData
{
    [self showWaitView:nil];
    
    NSString *flag = @"A90";
    int timestamp = (int)[[NSDate date]timeIntervalSince1970];
    NSString * checksum = [[NSString stringWithFormat:@"%d%@%d%@%dyaoxia",timestamp,flag,timestamp,self.queryId,timestamp]md5];
    NSString *URL_DETAIL = [NSString stringWithFormat:@"http://www.yaoxia.com/ajaxServlet?style=ae062a0f29297c33f8ab85b1d4b7741f&flag=%@&key=%@&timestamp=%d&checksum=%@",flag,self.queryId,timestamp,checksum];
    NSURL *url = [NSURL URLWithString:URL_DETAIL];
    request = [ASIHTTPRequest requestWithURL:url];
    [request setCompletionBlock:^{
        
        [self hideWaitView];
        
        // Use when fetching text data
        NSString *responseString = [request responseString];
        
        //NSLog(@"responseString = %@",responseString);
        //NSString *jsonStr = @"{\"code\":200,\"message\":\"成功\"}";
        id json = [responseString JSONValue];
        //NSLog(@"meg = %@",[json objectForKey:@"drugInfo"]);
        if ([[json objectForKey:@"code"]intValue] == 500) {
            NSLog(@"%@",[json objectForKey:@"message"]);
            UIAlertView *alert = [[UIAlertView alloc]
                                  initWithTitle:@"网络加载错误"
                                  message:@"无法连接到网络"/*[NSString stringWithFormat:@"%@",[json objectForKey:@"message"]]*/
                                  delegate:self
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil];
            [alert show];
            return ;
        }
        self.operationArray = [json objectForKey:@"drugInfo"];
        
        [self addOperationBtn];
        //[self.operationTableView reloadData];
        // Use when fetching binary data
        //NSData *responseData = [request responseData];
    }];
    [request setFailedBlock:^{
        
        [self hideWaitView];
        
        NSError *error = [request error];
        
        NSLog(@"error = %@",error);
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"无法连接到网络"
                              message:nil
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
    }];
    [request startAsynchronous];
    
}

-(void)addOperationBtn
{
    //NSLog(@"array = %@",self.operationArray);
    
    if (self.operationArray.count == 0) {
        return;
    }
    
    float row1_x = 20.0f;
    float row1_y = 200.0f;
    float step = 10.0f;
    int row_count = 3;
    float btn_width = (320.0f - row1_x*2 - step*(row_count -1))/3;
    float btn_height = btn_width + 3;
    
    
    for (int i = 0; i < self.operationArray.count; i++) {
        
        CGRect btnFrame = CGRectMake(row1_x + (i%row_count)*(btn_width + step), row1_y + (i/row_count)*(btn_height + step), btn_width, btn_height);
        UIButton *tempBtn = [[UIButton alloc]initWithFrame:btnFrame];
        NSString *tempTitle = [[self.operationArray objectAtIndex:i]objectForKey:@"infoName"];
        //NSString *tempUrl = [[self.operationArray objectAtIndex:i]objectForKey:@"url"];
        //[tempBtn setValue:[self.operationArray objectAtIndex:i] forKey:@"url"];
        [tempBtn setTag:i];
        [tempBtn addTarget:self action:@selector(showDetail:) forControlEvents:UIControlEventTouchUpInside];
        //[tempBtn setTitle:tempTitle forState:UIControlStateNormal];
        if ([@"警告" isEqualToString:tempTitle]) {
            [tempBtn setBackgroundImage:[UIImage imageNamed:@"drug_btn_jg.png"] forState:UIControlStateNormal];
        }
        else if ([@"用法" isEqualToString:tempTitle])
        {
            [tempBtn setBackgroundImage:[UIImage imageNamed:@"drug_btn_yf.png"] forState:UIControlStateNormal];
        }
        else if ([@"副作用" isEqualToString:tempTitle])
        {
            [tempBtn setBackgroundImage:[UIImage imageNamed:@"drug_btn_fzy.png"] forState:UIControlStateNormal];
        }
        else if ([@"注意事项" isEqualToString:tempTitle])
        {
            [tempBtn setBackgroundImage:[UIImage imageNamed:@"drug_btn_zysx.png"] forState:UIControlStateNormal];
        }
        else if ([@"相互作用" isEqualToString:tempTitle])
        {
            [tempBtn setBackgroundImage:[UIImage imageNamed:@"drug_btn_xhzy.png"] forState:UIControlStateNormal];
        }
        else if ([@"小贴士" isEqualToString:tempTitle])
        {
            [tempBtn setBackgroundImage:[UIImage imageNamed:@"drug_btn_xts.png"] forState:UIControlStateNormal];
        }
            
        [self.view addSubview:tempBtn];
    }
}

-(IBAction)showDetail:(id)sender
{
    NSDictionary *urlDetail = [self.operationArray objectAtIndex:[(UIButton *)sender tag]];
    //NSLog(@"url=%@",urlDetail);
    DrugWebViewController *webController = [[DrugWebViewController alloc]initWithNibName:@"DrugWebViewController" bundle:nil];
    webController.url = [urlDetail objectForKey:@"url"];
    webController.title = [urlDetail objectForKey:@"infoName"];
    
    [self.navigationController pushViewController:webController animated:YES];
}

-(void)setOperationView
{
    [self loadNetData];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    if(request != nil)
    {
        [request clearDelegatesAndCancel];
        request = nil;
    }
    if(request4Comment != nil)
    {
        [request4Comment clearDelegatesAndCancel];
        request4Comment = nil;
    }
    commonNameLabel = nil;
    nameLabel = nil;
    operationTableView = nil;
    overlayBtn = nil;
    name = nil;
    commonName = nil;
    brandName = nil;
    operationArray = nil;
    queryId = nil;
    self.nameView = nil;
    self.arrowIV = nil;
    self.diseaseArray = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(IBAction)searchDrugsLike:(id)sender
{
    //NSLog(@"button click!");
    DrugResultViewController *resultController = [[DrugResultViewController alloc]initWithNibName:@"DrugResultViewController" bundle:nil];
    
    resultController.drugQueryId = self.queryId;
    
    [self.navigationController pushViewController:resultController animated:YES];
    
}

//----------------tableview-----------------------
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    int numberOfRows = [self.operationArray count];
    CGRect oldFrame = tableView.frame;
    CGPoint oldOrigin = oldFrame.origin;
    CGFloat oldwidth =  oldFrame.size.width;
    CGFloat newHight = numberOfRows*RowHight;
    CGRect newFrame = CGRectMake(oldOrigin.x, oldOrigin.y, oldwidth, newHight);
    
    tableView.frame = newFrame;
    return  numberOfRows;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";
    UITableViewCell *cell = nil;
    NSInteger row;
    
    cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
    if (cell==nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
                                         reuseIdentifier:SimpleTableIdentifier];
    }
    row = [indexPath row];
        //NSLog(@"commArray at %d:%@",row,[commonArray objectAtIndex:row]);
    cell.textLabel.text = [[self.operationArray objectAtIndex:row]objectForKey:@"infoName"];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.textLabel.font = [UIFont systemFontOfSize:17.0f];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    int row = [indexPath row];
    NSDictionary *urlDetail = [self.operationArray objectAtIndex:row];
    //NSLog(@"url=%@",urlDetail);
    DrugWebViewController *webController = [[DrugWebViewController alloc]initWithNibName:@"DrugWebViewController" bundle:nil];
    webController.url = [urlDetail objectForKey:@"url"];
    webController.title = [urlDetail objectForKey:@"infoName"];
    
    [self.navigationController pushViewController:webController animated:YES];
}

//--------------评论部分----------------
-(IBAction)writeComment:(id)sender
{
    //写评论跳转
    [self loadDiseaseList];

}
-(void)loadDiseaseList
{
    [self showWaitView:nil];
    
    NSArray  * array= [self.name componentsSeparatedByString:@" "];
    NSString * nameStr = [NSString stringWithFormat:@"%@  %@",[array objectAtIndex:0],[array objectAtIndex:1]];
    NSLog(@"name=%@",nameStr);
    
    int timestamp = (int)[[NSDate date]timeIntervalSince1970];
    NSString * checksum = [[NSString stringWithFormat:@"%@%dyaoxia",self.queryId,timestamp]md5];
    
    NSString *URL_DETAIL = [NSString stringWithFormat:@"http://www.yaoxia.com/ajaxServlet"];
    NSURL *url = [NSURL URLWithString:URL_DETAIL];
    request4Comment = [ASIFormDataRequest requestWithURL:url];
    //www.yaoxia.com/ajaxServlet?style=getbaseinfo_lookformobile&drugid=$1&drugname=$2&timestamp=$3&checksum=$4
    [request4Comment setPostValue:@"getbaseinfo_lookformobile" forKey:@"style"];
    [request4Comment setPostValue:self.queryId forKey:@"drugid"];
    [request4Comment setPostValue:nameStr forKey:@"drugname"];
    [request4Comment setPostValue:[NSString stringWithFormat:@"%d",timestamp]  forKey:@"timestamp"];
    [request4Comment setPostValue:checksum forKey:@"checksum"];
    
    [request4Comment setCompletionBlock:^{
        
        [self hideWaitView];
        
        // Use when fetching text data
        NSString *responseString = [request4Comment responseString];
        
        //NSLog(@"responseString = %@",responseString);
        id json = [responseString JSONValue];
        if ([[json objectForKey:@"code"]intValue] == 500) {
            NSLog(@"%@",[json objectForKey:@"message"]);
            UIAlertView *alert = [[UIAlertView alloc]
                                  initWithTitle:@"网络加载错误"
                                  message:@"无法连接到网络"
                                  delegate:self
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil];
            [alert show];
            return ;
        }
        self.diseaseArray = [json objectForKey:@"array"];
        
        //NSLog(@"diseaseArray = %@",self.diseaseArray);
        
        WriteCommentViewController *detailController = [[WriteCommentViewController alloc]initWithNibName:@"WriteCommentViewController" bundle:nil];
        detailController.diseaseArray = self.diseaseArray;
        detailController.title = nameStr;
        [self.navigationController pushViewController:detailController animated:YES];
        // Use when fetching binary data
        //NSData *responseData = [request responseData];
    }];
    [request4Comment setFailedBlock:^{
        
        [self hideWaitView];
        
        NSError *error = [request4Comment error];
        
        NSLog(@"error = %@",error);
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"无法连接到网络"
                              message:nil
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
    }];
    [request4Comment startAsynchronous];
}


-(IBAction)showComment:(id)sender
{
    DiseaseListViewController *detailController = [[DiseaseListViewController alloc]initWithNibName:@"DiseaseListViewController" bundle:nil];
    detailController.name = self.name;
    detailController.queryId = self.queryId;
    [self.navigationController pushViewController:detailController animated:YES];
}

@end
